package com.palmar.proxy.handler.socks;

import com.palmar.proxy.safe.UserValidator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.socksx.v5.DefaultSocks5PasswordAuthRequest;
import io.netty.handler.codec.socksx.v5.DefaultSocks5PasswordAuthResponse;
import io.netty.handler.codec.socksx.v5.Socks5PasswordAuthStatus;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Scope("prototype")
public class SocksAuthenticationHandler extends SimpleChannelInboundHandler<DefaultSocks5PasswordAuthRequest> {

    @Resource
    private UserValidator validator;

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, DefaultSocks5PasswordAuthRequest
            auth) throws Exception {
        if (StringUtils.isBlank(auth.username()) || StringUtils.isBlank(auth.password())) {
            channelHandlerContext.writeAndFlush(new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus
                    .FAILURE)).addListener(ChannelFutureListener.CLOSE);
        }
        //验证账号密码
        boolean isOK = this.validator.validate(auth.username(), auth.password());
        //响应验证结果
        ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(new DefaultSocks5PasswordAuthResponse(isOK
                ? Socks5PasswordAuthStatus
                .SUCCESS : Socks5PasswordAuthStatus.FAILURE));
        if (!isOK) {
            //如果验证失败 关闭连接
            channelFuture.addListener(ChannelFutureListener.CLOSE);
        }
    }
}
